/**
 * 
 */
package be.bejug.scrumadmin.repository.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.ejb.HibernateEntityManager;

import be.bejug.scrumadmin.repository.GenericRepository;

/**
 * @author Glenn Dejaeger
 * 
 */
public class GenericRepositoryImpl<E, ID extends Serializable> implements
		GenericRepository<E, ID> {

	protected Class<E> entityClass;

	@PersistenceContext
	protected EntityManager em;

	@SuppressWarnings("unchecked")
	public GenericRepositoryImpl() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		this.entityClass = (Class<E>) genericSuperclass
				.getActualTypeArguments()[0];
	}

	@Override
	public E save(final E entity) {
		return em.merge(entity);
	}

	@Override
	public void remove(final E entity) {
		em.remove(entity);
	}

	@Override
	public E findById(final ID id) {
		return em.find(entityClass, id);
	}

	/**
	 * Use this inside subclasses as a convenience method.
	 */
	protected List<E> findByCriteria(final Criterion... criterion) {
		return findByCriteria(-1, -1, criterion);
	}

	/**
	 * Use this inside subclasses as a convenience method.
	 */
	@SuppressWarnings("unchecked")
	protected List<E> findByCriteria(final int firstResult,
			final int maxResults, final Criterion... criterion) {
		HibernateEntityManager hem = (HibernateEntityManager) em;
		Criteria crit = hem.getSession().createCriteria(entityClass);

		for (final Criterion c : criterion) {
			crit.add(c);
		}

		if (firstResult > 0) {
			crit.setFirstResult(firstResult);
		}

		if (maxResults > 0) {
			crit.setMaxResults(maxResults);
		}

		final List<E> result = crit.list();
		return result;
	}

	@Override
	public List<E> findAll() {
		return findByCriteria();
	}

	/**
	 * @return the entityManager
	 */
	public EntityManager getEntityManager() {
		return em;
	}
}